<script lang="ts" setup>
import { getCommonCourseTags } from '@/api/study/studySquare';
import { message } from 'ant-design-vue';
import { onMounted, ref } from 'vue';
import type { CourseItem } from '@/views/Square/LearningSquare/Course/home/types/CourseItem';
import axios from 'axios';
import CourseCard from '@/views/Square/LearningSquare/Course/home/components/CourseCard.vue';

const searchQuery = ref<string>('');
const filterOptions = ref<{ tagName: string, tagId: string }[]>([]);
const selectedFilter = ref<string>('全部');
const currentPageIndex = ref<number>(1);
const courseItems = ref<CourseItem[]>([]);
const columnNum = ref<number>(4);

const onAdviceBtnClicked = () => {
  window.open(import.meta.env.VITE_ADVICE_URL, '_blank');
}

const fetchFilterOptions = async () => {
  try {
    const response = await getCommonCourseTags();
    filterOptions.value = [{ tagName: '全部', tagId: '' },
      ...response.map((tagName: string, index: number) => ({
        tagName,
        tagId: index.toString(),
      }))];
  }
  catch (error) {
    console.error('Failed to fetch categories:', error);
    message.error('请求标签时出现错误');
  }
};

// 获取 Cookie 中的 Access Token 的辅助函数
const getCookieValue = (name: string): string | null => {
  const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`));
  return match ? decodeURIComponent(match[2]) : null;
};

// 获取课程数据
const fetchCourseMetadata = async () => {
  const accessToken_java = getCookieValue('access_token_lf');
  if (!accessToken_java) {
    message.error('未检测到访问令牌');
    return;
  }

  const requestBody = {
    keywords: searchQuery.value || '',
    tag: selectedFilter.value === '全部' ? '' : selectedFilter.value,
    page: currentPageIndex.value.toString(),
    size: '100',
  };

  try {
    const response = await axios.post(
      '/java/ground/study/course/get_course_metadata',
      requestBody,
      {
        headers: {
          "Authorization": `Bearer ${accessToken_java}`,
          'Content-Type': 'application/json',
        },
      },
    );

    if (response.status === 200 && response.data?.data) {
      courseItems.value = response.data.data.records;
    }
    else {
      console.error('Error in response:', response.data);
      message.error('获取课程数据失败');
    }
  }
  catch (error) {
    console.error('Request failed:', error);
    message.error('获取课程数据时出现错误');
  }
};

const onSearchBtnClicked = () => {
  currentPageIndex.value = 1;
  fetchCourseMetadata();
};

const onFilterBtnClicked = (option: string) => {
  selectedFilter.value = option;
  currentPageIndex.value = 1;
  fetchCourseMetadata();
};

onMounted(() => {
  fetchFilterOptions();
  fetchCourseMetadata();
});
</script>

<template>
  <a-layout v-show="$route.meta.showHome" class="home-layout">
    <div class="flex flex-row justify-between items-center mx-4 my-2">
      <!-- 面包屑导航 -->
      <a-breadcrumb class="text-3xl font-bold flex items-center gap-2">
        <a-breadcrumb-item>
          <router-link to="/user/learningNew/skill-tree" style="height: 100%;">
            学习广场
          </router-link>
        </a-breadcrumb-item>

        <a-breadcrumb-item class="flex items-center relative">
          课程
          <img
            src="@/assets/title_star.svg"
            alt="课程"
            class="w-6 h-6 absolute -right-6"
          >
        </a-breadcrumb-item>
      </a-breadcrumb>

      <div class="flex flex-row gap-2">
        <a-button type="primary" style="width: 30%;" @click="onAdviceBtnClicked">
          提建议
        </a-button>

        <!-- 搜索框 -->
        <a-input-search
          v-model:value="searchQuery"
          placeholder="搜索课程"
          :enter-button="true"
          @search="onSearchBtnClicked"
        />
      </div>
    </div>

    <!-- 标签过滤器 -->
    <a-flex style="flex-wrap: wrap; gap: 0.5rem; margin: 0rem 1rem;">
      <a-button
        v-for="option in filterOptions"
        :key="option.tagId"
        :type="option.tagName === selectedFilter ? 'primary' : 'default'"
        @click="onFilterBtnClicked(option.tagName)"
      >
        {{ option.tagName }}
      </a-button>
    </a-flex>

    <!-- 技能树Market -->
    <div style="flex: 1; overflow: auto; margin-top: 1rem; margin-bottom: 0.5rem;">
      <!-- 先使用一层div包裹，再使用a-row和a-col -->
      <div style="margin-left: 1rem; margin-right: 1rem;">
        <a-row :gutter="[10, 10]">
          <a-col v-for="item in courseItems" :key="item.courseId" :span="24 / columnNum">
            <CourseCard :course-item="item" />
          </a-col>
        </a-row>
      </div>
    </div>
  </a-layout>

  <router-view />
</template>

<style scoped lang="scss">
.home-layout {
  display: flex;
  flex-direction: column;
  height: 100%;

  background-color: transparent;
}
</style>
